('use strict');
import 'whatwg-fetch';
import * as Immutable from 'immutable';
import { $http } from '../../../util/index';
import xSiteOpenApi from '@qianmi/x-site-openapi';
import {
  getAdminD2cApiHost,
  getSessionId,
  getEnvXSite,
} from '../../../util/index';
declare let window: any;
const tplCodeList = [
  'weixin-newFruit',
  'weixin-newLifeSupplies',
  'weixin-newFood',
];
const thePageCode = '_page_code_4_mobile';
const theWidgetName =
  'x-site-ui-wechat/widget-bar/slider-bar/slider-common-bar';
/**
 * 查询用户个人信息
 * 然后储存下来，包括账户安全相关信息
 */
export const fetchTemplateList = async (): Promise<any> => {
  try {
    let { PageService, tplInfoService } = await xSiteOpenApi($http);
    // let templateList = await TplService.getTplListByTplCodes(tplCodeList);
    let templateList = await tplInfoService.getTplListByTplCodes(tplCodeList);
    let pageInfo: any = await PageService.getDetailPageInfo({
      platform: 'weixin',
      pageType: 'index',
      pageCode: thePageCode,
    });
    let curTplCode = pageInfo ? pageInfo.tplCode : '';
    let content = '';
    if (pageInfo && pageInfo.configOrder) {
      Immutable.fromJS(pageInfo.configOrder)
        .get('children')
        .forEach(widget => {
          if (!content && widget.get('widgetNameSpace') === theWidgetName) {
            content = widget.getIn(['props', 'items', 0, 'content']);
          }
        });
    }
    return templateList.map(item => {
      return {
        name: item.tplInfoName,
        image: item.detailInfo.previewImage,
        id: item.templateCode,
        activated: curTplCode === item.templateCode && pageInfo.activated,
        content: curTplCode === item.templateCode ? content : '',
      };
    });
  } catch (e) {
    throw e;
  }
};
export const Release = async () => {
  // let { BusCfgService } = await xSiteOpenApi($http);
  // let result = await BusCfgService.hasBeenEditedInPC();
  try {
    let result: any = await new Promise((resolve, reject) => {
      fetch(
        getEnvXSite() +
          '/xsite-bin/bus-cfg-svc/hasBeenEditedInPC?sc=H4sIAAAAAAAAA0sxSg4uyS9KBQDJOKt4CAAAAA==',
        {
          method: 'GET',
          mode: 'cors',
          credentials: 'include',
          headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json',
            Authorization: getSessionId(),
          },
        }
      ).then(
        response => {
          if (response.status !== 200) {
            reject(response);
          } else {
            response.json().then(result => {
              resolve(result);
            });
          }
        },
        err => {
          reject(err);
        }
      );
    });
    return { release: result.data };
  } catch (e) {
    console.error(e);
    return { release: true };
  }
};

export const publish = async ({
  tplCode,
  url,
}: {
  tplCode: string;
  url: string;
}) => {
  try {
    let { PageService, PublishService } = await xSiteOpenApi($http);
    let defaultPageInfo = await PageService.getPageInfoByTplCode(tplCode);
    defaultPageInfo.pageCode = thePageCode;
    defaultPageInfo.activated = true;
    if (url) {
      defaultPageInfo.configOrder = Immutable.fromJS(
        defaultPageInfo.configOrder
      )
        .update('children', widgetList => {
          return widgetList.map(widget => {
            if (widget.get('widgetNameSpace') === theWidgetName) {
              widget = widget.setIn(['props', 'items', 0, 'content'], url);
            }
            return widget;
          });
        })
        .toJS();
    }
    await PublishService.publish({
      pageInfo: defaultPageInfo,
      ignoreVisualScene: true,
    });
    return await PublishService.saveInfo({
      pageInfo: defaultPageInfo,
      justSave: false,
    });
  } catch (e) {
    throw e;
  }
};

export const fetchDomainUrl = async () => {
  let url = '';
  let result: any = {};
  try {
    result = await new Promise((resolve, reject) => {
      fetch(getAdminD2cApiHost() + '/domain/list', {
        method: 'POST',
        headers: {
          Accept: 'application/json',
          'Content-Type': 'application/json',
          Authorization: getSessionId(),
          credentials: 'omit',
        },
        body: JSON.stringify(['w']),
      }).then(
        response => {
          if (response.status !== 200) {
            reject(response);
          } else {
            response.json().then(result => {
              resolve(result);
            });
          }
        },
        err => {
          reject(err);
        }
      );
    });
  } catch (e) {
    console.error(e);
  }
  if (result.status == 1 && result.data.length > 0) {
    result.data.forEach(item => {
      let { dtype, domainDefault, domainUrl } = item;
      if (dtype === 'w' && domainDefault === 'Y') {
        url = domainUrl;
      }
    });
  }
  return url;
};

export const backgroundList = async () => {
  return Promise.resolve([
    {
      bannerImage:
        '//qianmi-web.oss-cn-hangzhou.aliyuncs.com/x-site/public/x-site-ui-wechat/statics/app-xsite/default-background-1.jpeg',
      id: '2017062111111',
    },
    {
      bannerImage:
        '//qianmi-web.oss-cn-hangzhou.aliyuncs.com/x-site/public/x-site-ui-wechat/statics/app-xsite/default-background-2.jpeg',
      id: '201706211112',
    },
    {
      bannerImage:
        '//qianmi-web.oss-cn-hangzhou.aliyuncs.com/x-site/public/x-site-ui-wechat/statics/app-xsite/default-background-3.jpeg',
      id: '201706211113',
    },
    {
      bannerImage:
        '//qianmi-web.oss-cn-hangzhou.aliyuncs.com/x-site/public/x-site-ui-wechat/statics/app-xsite/default-background-4.jpeg',
      id: '201706211114',
    },
    {
      bannerImage:
        '//qianmi-web.oss-cn-hangzhou.aliyuncs.com/x-site/public/x-site-ui-wechat/statics/app-xsite/default-background-5.jpeg',
      id: '201706211115',
    },
    {
      bannerImage:
        '//qianmi-web.oss-cn-hangzhou.aliyuncs.com/x-site/public/x-site-ui-wechat/statics/app-xsite/default-background-6.jpeg',
      id: '201706211116',
    },
    {
      bannerImage:
        '//qianmi-web.oss-cn-hangzhou.aliyuncs.com/x-site/public/x-site-ui-wechat/statics/app-xsite/default-background-7.jpeg',
      id: '201706211117',
    },
    {
      bannerImage:
        '//qianmi-web.oss-cn-hangzhou.aliyuncs.com/x-site/public/x-site-ui-wechat/statics/app-xsite/default-background-8.jpeg',
      id: '201706211118',
    },
  ]);
};
// fetchUserInfo.then(data=>{
//     console.log(data);
// })
